<template>
  <div :style="bottomStaySpace()" class="wrap">
    <LabelAndValue :box-style="labelValueStyle" colon label="日程名称" label-width="210" required>
      <Input v-model:value="form.name" placeholder="请输入日程名称" />
    </LabelAndValue>
    <LabelAndValue :box-style="labelValueStyle" colon label="日程类型" label-width="210" required>
      <RadioSelect v-model:value="form.activityType" :config="scheduleType" position="left" />
    </LabelAndValue>
    <LabelAndValue :box-style="labelValueStyle" colon label="开始时间" label-width="210" required @tap="startTimeRef.change()">
      <div class="select flex_sb_cen">
        <span :style="{color: form.beginTimeText ? '' : 'rgba(0, 0, 0, 0.25)'}">{{ form.beginTimeText || '请选择开始时间' }}</span>
        <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
      </div>
    </LabelAndValue>
    <LabelAndValue :box-style="labelValueStyle" colon label="结束时间" label-width="210" required @tap="endTimeRef.change()">
      <div class="select flex_sb_cen">
        <span :style="{color: form.endTimeText ? '' : 'rgba(0, 0, 0, 0.25)'}">{{ form.endTimeText || '请选择结束时间' }}</span>
        <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
      </div>
    </LabelAndValue>
    <LabelAndValue :box-style="labelValueStyle" colon label="地区" label-width="210" required @tap="areaRef.change()">
      <div class="select flex_sb_cen">
        <span :style="{color: form.province ? '' : 'rgba(0, 0, 0, 0.25)'}">{{ form.province ? `${form.province}-${form.city}` : '请选择所在地区' }}</span>
        <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
      </div>
    </LabelAndValue>
    <LabelAndValue :box-style="labelValueStyle" :required="joinMainBodyList?.length > 0" colon label="参与主体" label-width="210" @tap="selectJoinMainBodyFn">
      <div class="select flex_sb_cen">
        <div v-if="joinMainBodyList?.some(item => item.checked === true)" class="textLineHidden" style="width: 420rpx">
          <span v-for="(item, index) in joinMainBodyList" :key="item.id">
            {{ item.checked ? `${item.name}${item.mobile}` : '' }}{{ index < joinMainBodyList.filter(item1 => item1.checked)?.length - 1 ? ' | ' : '' }}
          </span>
        </div>
        <span v-else style="color: rgba(0, 0, 0, 0.25);">请选择参与主体</span>
        <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
      </div>
    </LabelAndValue>
    <LabelAndValue :box-style="labelValueStyle" colon label="备注" label-width="210" @tap="notesRef.change()">
      <div class="select flex_sb_cen">
        <div :style="{color: form.remarkText ? '' : 'rgba(0, 0, 0, 0.25)', width: '420rpx'}" class="textLineHidden">{{ form.remarkText || '请输入备注' }}</div>
        <Icon :styles="{opacity: 0.5}" name="icon-youjiantou" size="30" />
      </div>
    </LabelAndValue>
    <div :style="keepBottomSafeDis()" class="suction_bottom_btn">
      <Button :disabled="isDisabled" size="L" @confirm="confirmFn">{{ form.id ? '保存' : '立即创建' }}</Button>
    </div>
    <!-- 开始时间 -->
    <Drawer ref="startTimeRef">
      <DateSelect :is-show-time-period-select="true" :min="minDate" title="请选择开始时间" @cancel="startTimeRef.change()" @value="startTimeFn" />
    </Drawer>
    <!-- 结束时间 -->
    <Drawer ref="endTimeRef">
      <DateSelect :is-show-time-period-select="true" :min="minDate" title="请选择结束时间" @cancel="endTimeRef.change()" @value="endTimeFn" />
    </Drawer>
    <!-- 地区 -->
    <Drawer ref="areaRef">
      <SiteSelect :columns-num="2" @cancel="areaRef.change()" @value="setAreaFn" />
    </Drawer>
    <!-- 参与主体 -->
    <Drawer ref="joinMainBodyRef">
      <div class="popup_box">
        <div class="popup_title">
          <div>参与主体</div>
          <div class="icon_close" @tap="joinMainBodyRef.change()">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div class="popup_body">
          <div class="flex_end mt20" @tap="selectAllBodyFn">
            <span class="mr12">全选</span>
            <Icon v-if="isAllSelect" name="icon-a-bianzu17" size="32" />
            <Icon v-else name="icon-a-Rectangle271Copy10" size="32" />
          </div>
          <div v-for="(item, index) in joinMainBodyList" :key="index" class="way_item flex_sb_cen" @tap="selectBodyFn(item.id)">
            <div>{{ item.name }}{{ item.mobile }}</div>
            <div v-if="item.checked">
              <Icon name="icon-duoxuankuanger" width="32" />
            </div>
            <div v-else>
              <Icon name="icon-a-Rectangle271Copy10" width="32" />
            </div>
          </div>
        </div>
        <div :style="keepBottomSafeDis()" class="flex_cen_cen mt20">
          <Button size="L" @confirm="confirmBodyFn">确定</Button>
        </div>
      </div>
    </Drawer>
    <!-- 备注 -->
    <Drawer ref="notesRef">
      <div class="popup_box">
        <div class="popup_title">
          <div>备注</div>
          <div class="icon_close" @tap="notesRef.change()">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div class="mt16  popup_body">
          <up-textarea v-model="form.remark" count height="100" maxlength="200" placeholder="请输入备注" />
        </div>
        <div :style="keepBottomSafeDis()" class="mt26 flex_cen_cen">
          <Button size="L" @tap="confirmNotesFn">确定</Button>
        </div>
      </div>
    </Drawer>
  </div>
</template>
<script lang="ts" setup>
import { bottomStaySpace, keepBottomSafeDis, Router, onLoad, onUnload } from '@U/common'
import Input from '@C/Input.vue'
import LabelAndValue from '@C/LabelAndValue.vue'
import { reactive, computed, ref } from 'vue'
import RadioSelect from '@C/RadioSelect.vue'
import Icon from '@C/Icon.vue'
import Drawer from '@C/Drawer.vue'
import DateSelect from '@C/DateSelect.vue'
import getDate from '@U/getDate'
import SiteSelect from '@C/SiteSelect.vue'
import Button from '@C/Button.vue'
import { Msg } from '@C/Msg'
import { createActivitySchedule, getJoinMainBodyList, updateActivitySchedule } from '@P_GL/activitySchedule/request'
import dayjs from 'dayjs'
import { IObj } from '@/interface'

// 组件样式
const labelValueStyle = { borderBottom: '1rpx solid rgba(0,0,0,0.1)', height: '86rpx', marginTop: '40rpx', paddingRight: 0 }
const nowDate = getDate() as IObj
const minDate = computed(() => `${nowDate.Y}-${nowDate.M}-${nowDate.D}`)
const currentDate = dayjs(new Date()).format('YYYY-MM-DD')
const form = reactive({
  id: '',
  name: '',
  activityType: 1,
  beginTime: nowDate.h > 12 ? `${currentDate} 14:00:00` : `${currentDate} 10:00:00`,
  beginTimeText: nowDate.h > 12 ? `${currentDate} 下午` : `${currentDate} 上午`,
  endTime: `${currentDate} 14:00:00`,
  endTimeText: `${currentDate} 下午`,
  province: '',
  provinceCode: '',
  city: '',
  cityCode: '',
  participants: [],
  remark: '',
  remarkText: '',
})
const scheduleType = [
  { label: '线上', key: 0 },
  { label: '线下', key: 1 },
]
// 开始时间
const startTimeRef = ref()
const startTimeFn = (startTime: string) => {
  const startTimeArr = startTime.split(' ')
  // 当天下午不能创建上午的日程
  if (startTimeArr[0] === currentDate && startTimeArr[1] === '10:00:00' && nowDate.h > 12) return Msg({ msg: '当前时间不能创建上午的日程' })
  form.beginTime = startTime
  let timeText = ''
  if (startTimeArr[1] === '10:00:00') timeText = '上午'
  if (startTimeArr[1] === '14:00:00') timeText = '下午'
  form.beginTimeText = `${startTime.split(' ')[0]} ${timeText}`
  startTimeRef.value.change()
}
// 结束时间
const endTimeRef = ref()
const endTimeFn = (endTime: string) => {
  const endTimeArr = endTime.split(' ')
  // 当天下午不能创建上午的日程
  if (endTimeArr[0] === currentDate && endTimeArr[1] === '10:00:00' && nowDate.h > 12) return Msg({ msg: '当前时间不能创建上午的日程' })
  form.endTime = endTime
  let timeText = ''
  if (endTimeArr[1] === '10:00:00') timeText = '上午'
  if (endTimeArr[1] === '14:00:00') timeText = '下午'
  form.endTimeText = `${endTime.split(' ')[0]} ${timeText}`
  endTimeRef.value.change()
}
const areaRef = ref()
const setAreaFn = (e: IObj) => {
  form.province = e.province.name
  form.provinceCode = e.province.code
  form.city = e.city.name
  form.cityCode = e.city.code
  areaRef.value.change()
}
const joinMainBodyList = ref([])
const joinMainBodyRef = ref()
const selectJoinMainBodyFn = () => {
  if (joinMainBodyList.value?.length < 1) return Msg({ msg: '您当前没有可参与的主体' })
  joinMainBodyRef.value.change()
}
const selectAllBodyFn = () => {
  if (joinMainBodyList.value.some(item => item.checked === false)) joinMainBodyList.value.forEach(item1 => item1.checked = true)
  else joinMainBodyList.value.forEach(item2 => item2.checked = false)
}
const isAllSelect = computed(() => joinMainBodyList.value?.every(item => item.checked === true))
const selectBodyFn = (id: number) => {
  const joinMainBodyInfo = joinMainBodyList.value.find(item => item.id === id)
  joinMainBodyInfo.checked = !joinMainBodyInfo.checked
}
const confirmBodyFn = () => {
  if (joinMainBodyList.value.every(item => item.checked === false)) return Msg({ msg: '请先选择参与主体' })
  form.participants = joinMainBodyList.value.filter(item => item.checked).map(item => item.id)
  joinMainBodyRef.value.change()
}
const notesRef = ref()
const confirmNotesFn = () => {
  if (!form.remark) return Msg({ msg: '请先输入备注' })
  form.remarkText = form.remark
  notesRef.value.change()
}
const isDisabled = computed(() => !form.name
    || !form.beginTime
    || !form.endTime
    || !form.provinceCode
    || !form.cityCode
    || (joinMainBodyList.value?.length > 0 ? !(form.participants?.length > 0) : false))
    || !form.remark
const confirmFn = async () => {
  if (isDisabled.value) return
  if (dayjs(form.endTime).valueOf() < dayjs(form.beginTime).valueOf()) return Msg({ msg: '结束时间不能早于开始时间' })
  let res = {}
  if (form.id) res = await updateActivitySchedule(form).finally(() => {})
  else res = await createActivitySchedule(form).finally(() => {})
  if (res?.code === 200) {
    Router.back()
    uni.$emit('getScheduleDetailsFn')
  }
}
const getJoinMainBodyListFn = async () => {
  const res = await getJoinMainBodyList().finally(() => {})
  if (res?.code === 200) {
    joinMainBodyList.value = res.data.map(item => ({
        id: item.id,
        name: item.name,
        mobile: item.mobile.slice(-4),
        checked: false,
    }))
  }
}
onLoad(async (options) => {
  await getJoinMainBodyListFn()
  if (options?.scheduleDetails) {
    for (const key in JSON.parse(options.scheduleDetails)) {
      form[key] = JSON.parse(options.scheduleDetails)[key]
    }
    form.remarkText = form.remark
    joinMainBodyList.value.forEach(item => {
      if (form.participants.includes(item.id)) item.checked = true
    })
  }
})
onUnload(() => {
  uni.$off('getScheduleDetailsFn')
})
</script>

<style lang="less" scoped>
.wrap {
  padding: 0 24rpx;
  background-color: #fff;
  .select {
    font-size: 28rpx;
    line-height: 86rpx;
  }
  .popup_box {
    .way_item {
      font-weight: 400;
      font-size: 32rpx;
      color: rgba(0,0,0,0.85);
      line-height: 34rpx;
      padding-bottom: 34rpx;
      margin-top: 30rpx;
    }
  }
}
</style>
